<template>
    <div class="shopContainer">
        <div class="shopbody">
            <div class="menu-wrapper" ref="menuWrapper">
                <div v-for="(obj,index) in foodList" :key="index" 
                    :class="{current: index===currentIndex}" @click="clickMenuItem(index)">
                    <!-- 动态切换class，current这个class存在与否，取决于后面的逻辑 -->
                    <p>{{obj.foodGroup}}</p>
                </div>
            </div>
            <div class="foods-wrapper" ref="foodsWrapper">
                <ul ref="foodsUl" class="display:inline-block">
                    <li class="food-list-hook"  v-for="(obj,index) in foodList" :key="index">
                        <p style="background-color:#f1f1f1;line-height: 2.8rem;">{{obj.foodGroup}}</p>
                        <ul>
                            <li v-for="(item,i) in obj.groupList" :key="i" class="foodBody">
                                <div class="itema">
                                    <img :src="item.foodUrl">
                                </div>
                                <div class="itemb">{{item.foodName}}</div>
                                <div class="itemc">{{item.foodInfo}}</div>
                                <div class="itemd">
                                    月售{{item.foodNumber}} 好评率{{item.foodGood}}%
                                    <p v-if="item.foodLimit!='-1'">限{{item.foodLimit}}份</p>
                                    <p v-if="item.foodRest!='-1'&&item.foodRest!='0'">剩{{item.foodRest}}份</p>
                                    <p v-if="item.foodRest=='0'">已售完</p>
                                </div>
                                <div class="iteme">￥{{item.foodMoney/100}}</div>
                                <div class="itemf">
                                    <p class="pbutton" @click.prevent="updateFoodCount(false,item.foodid,item.foodName,item.foodUrl,item.foodMoney,item.foodPack)">-</p>
                                    <p v-if="cartFoods[item.foodid]!=undefined">{{cartFoods[item.foodid].count}}</p>
                                    <p class="pbutton" @click.prevent="updateFoodCount(true,item.foodid,item.foodName,item.foodUrl,item.foodMoney,item.foodPack)">+</p>
                                </div>
                            </li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
        <div class="shopFooter">
            <div class="itema">
                <div class="imgContainer">
                    <img src="../images/购物车.svg" width="50px" height="50px" @click="cartDrawer=!cartDrawer">
                    <p v-if="cartMessage.count!=0" class="popnum">{{cartMessage.count}}</p>
                </div>
            </div>
            <div class="itemb">
                <div>
                    <p class="cost1">￥{{cutSum/100}}</p>
                    <p class="cost2" v-if="cutSum!=cartMessage.sum">￥{{cartMessage.sum/100}}</p>
                </div>
                <div>
                    <p class="cost2" style="text-decoration:none">另需配送费￥{{(distributionCost-peisong)/100}}</p>
                    <p class="cost2" v-if="peisong!=0">￥{{distributionCost/100}}</p>
                </div>
            </div>
            <router-link to='account' style="text-decoration: none">
                <div class="itemc">去结算</div>
            </router-link>
        </div>
        <el-card class="box-card drawerclass" v-if="cartDrawer">
            <div slot="header" class="clearfix">
                <span>已选商品</span><span v-if="reductionCut[0]!=0"> 满{{reductionCut[0]}}减{{reductionCut[1]}}</span>
                <span v-if="baiyiCut[0]!=0"> 百亿补贴满{{baiyiCut[0]}}减{{baiyiCut[1]}}</span>
                <img @click.prevent="clearCart" src="../images/垃圾桶.svg" width="30px" height="30px">
            </div>
            <div v-for="(obj,index) in cartFoods" :key="index" class="cartBox">
                <div class="itema"><img :src="cartFoods[index].foodUrl" width="70px" height="70px"></div>
                <div class="itemb">{{cartFoods[index].foodName}}</div>
                <div class="itemc">
                    <p class="pbutton" @click.prevent="updateFoodCount(false,index,cartFoods[index].foodName,cartFoods[index].foodUrl,cartFoods[index].foodMoney,cartFoods[index].foodPack)">-</p>
                    <p v-if="cartFoods[index]!=undefined">{{cartFoods[index].count}}</p>
                    <p class="pbutton" @click.prevent="updateFoodCount(true,index,cartFoods[index].foodName,cartFoods[index].foodUrl,cartFoods[index].foodMoney,cartFoods[index].foodPack)">+</p>
                </div>
                <div class="itemd">￥{{(cartFoods[index].count*cartFoods[index].foodMoney)/100}}</div>
            </div>
        </el-card>
    </div>
</template>
<script>
    import BScroll from 'better-scroll'
    import axios from 'axios'
    import {mapState,mapMutations} from 'vuex'
    export default({
        data(){
            return{
                scrollY:0,//右侧滑动的Y轴坐标（实时变化）
                tops:[],//所有右侧分类的div的top组成的数组（列表第一次显示就不再变化）
                cartDrawer:false,
                reductionCut:[0,0],
                baiyiCut:[0,0],
            }
        },
        props:['distributionCost','reduction','baiyi','peisong'],
        mounted(){
            //每次进入新商家，foodList要重置,购物车也要重置,再分别获取
            this.clearFoodList();
            this.clearCart();
            let url='/shop/selectmenu/'+this.shopId;
            this.getRequest(url,null,null).then(response=>{
                if(response.code==200){
                    for(let item in response.obj){
                        let arr={
                            foodGroup:item,
                            groupList:response.obj[item],
                        };
                        for(let index in arr.groupList){
                            arr.groupList[index].foodUrl="/file"+arr.groupList[index].foodUrl;
                        }
                        this.addFoodList(arr);
                    }
                    //如果真实数据 这两个方法放在this.$nextTick()里面
                    this.$nextTick(() => {
                        this._initScroll();
                        this._initTops();
                    });
                }
            });
            this.getShopCart();//获取购物车记录
        },
        computed:{
            ...mapState(['cartFoods','foodList','cartMessage','shopId']),
            // 计算当前分类的index，在初始和数据发生变化时触发
            currentIndex() {
                //得到条件数据
                const {scrollY,tops}=this
                //根据条件计算产生一个结果
                const index=tops.findIndex((top,index)=>{
                    return scrollY>=top&&scrollY<tops[index+1];
                })
                //返回结果
                return index;
            },
            cutSum(){//满减以后的价格
                let max_l=0;
                let max_r=0;
                for(let item in this.reduction){
                    if(this.reduction[item][0]>max_l&&this.cartMessage.sum>=this.reduction[item][0]*100){
                        max_l=this.reduction[item][0];
                        max_r=this.reduction[item][1];
                    }
                }
                this.reductionCut=[max_l,max_r];
                if(this.cartMessage.sum>=this.baiyi[0]*100)
                    this.baiyiCut=this.baiyi;
                else this.baiyiCut=[0,0];
                let obj1={name:'reductionCut',value:this.reductionCut};
                let obj2={name:'baiyiCut',value:this.baiyiCut};
                this.setReduction(obj1);
                this.setReduction(obj2);
                return this.cartMessage.sum-max_r*100-this.baiyiCut[1]*100;
            }
        },
        methods:{
            ...mapMutations(['addFoodCount','deleteFoodCount','clearCart','setReduction','setCartFoods','setCartMessage','addFoodList','clearFoodList']),
            updateFoodCount(isAdd,food,name,url,money,packcost){
                this.$store.dispatch('updateFoodCount',{isAdd,food,name,url,money,packcost});
                this.setShopCart();
            },
            //初始化scrollY
            _initScroll(){
                //列表显示后创建
                new BScroll(this.$refs.menuWrapper,{
                    click:true
                })
                this.foodsScroll=new BScroll(this.$refs.foodsWrapper,{
                    probeType:2,//因为惯性滑动不会触发
                    click:true,
                })
                //给右侧列表绑定scroll监听(x,y是坐标)
                this.foodsScroll.on('scroll',(event)=>{
                    this.scrollY=Math.abs(event.y);
                })
                //惯性滑动后也触发
                this.foodsScroll.on('scrollEnd',(event)=>{
                    this.scrollY=Math.abs(event.y);
                })
            },
            //初始化tops
            _initTops(){
                //1.初始化tops
                const tops=[];
                let top=0;
                tops.push(top);
                //2.收集
                //找到所有分类的div
                const lis=this.$refs.foodsUl.getElementsByClassName('food-list-hook');
                Array.prototype.slice.call(lis).forEach(div=>{
                    top+=div.clientHeight;
                    tops.push(top);
                })
                //3.更新数据
                this.tops=tops;
            },
            //让右侧列表滑动到对应的位置
            clickMenuItem(index){
                //得到目标位置的Y坐标，并立即更新点击的分类
                const scrollY=this.tops[index];
                this.scrollY = scrollY
                //平滑滑动右侧列表
                this.foodsScroll.scrollTo(0,-scrollY,300)
            },
            async getShopCart(){
                if(window.sessionStorage.getItem('tokenStr')){
                    let tokenStr=window.sessionStorage.getItem('tokenStr');
                    let url='/users/getShopCart/'+this.shopId;
                    await this.postRequest(url,'',tokenStr).then(response=>{
                        if(response.code==200){
                            if(response.obj==null||response.obj.msg==undefined||response.obj.msg.length==0){//暂无购物车记录
                                let obj1={};
                                this.setCartFoods(obj1);
                                let obj2={
                                    count:0,
                                    sum:0
                                };
                                this.setCartMessage(obj2);
                            }else{
                                this.setCartFoods(response.obj.msg.cartFoods);
                                this.setCartMessage(response.obj.msg.cartMessage);
                            }
                        }
                    })
                }
            },
            setShopCart(){
                if(window.sessionStorage.getItem('tokenStr')){
                    let tokenStr=window.sessionStorage.getItem('tokenStr');
                    let postDate={
                        msg:{
                            cartFoods:this.cartFoods,
                            cartMessage:this.cartMessage
                        }
                    }
                    let url='/users/setShopCart/'+this.shopId;
                    this.postRequest(url,postDate,tokenStr).then(response=>{
                        if(response.code==200){
                            console.log('后端购物车记录更新成功');
                        }
                    })
                }
            }
        }
    })
</script>
<style lang="scss" scoped>
    @import 'mint-ui/lib/style.css';
    @import '../style/mixin';
    *{
        margin: 0;
        padding: 0;
    }
    li{
        list-style: none;
    }
    ul{
        list-style: none;
    }
    .shopContainer{
        position: relative;
        .shopbody{
            display: grid;
            grid-template-columns:20% 80%;
            grid-template-rows:100%;
            // @include width-height(100%,70vh);最后一行有点问题
            .menu-wrapper{
                @include width-height(100%,70vh);
                background-color: #f5f5f5;
                overflow: auto;//内容超过指定高度，出现滚动条
                .current{
                    background-color:#fff;
                    border-left: 5px solid #26a2ff;
                }
                p{
                    border-left: 5px solid #f5f5f5;
                    line-height: 4rem;
                    padding-left:0.5rem;
                    @include font-size-color(1.1rem,#666);
                    border-bottom:1px solid #e1e1e1;
                }
            }
            .foods-wrapper{
                @include width-height(100%,70vh);
                overflow: auto;//内容超过指定高度，出现滚动条
                p{
                    @include font-size-color(1.4rem,#666);
                    height: 2.8rem;
                    padding-left:1rem;
                }
                .foodBody{
                    border-bottom:1.5px solid #f1f1f1;
                    padding: 0.5rem 0 0 0.5rem;
                    display: grid;
                    @include width-height(100%,7.2rem);
                    background-color:#fff;
                    grid-template-columns: 20% 45% 35%;
                    grid-template-rows: 25% 25% 25% 25%;
                    grid-template-areas: "a b b"
                                        "a c c"
                                        ". d d"
                                        ". e f";
                    .itema{
                        grid-area: a;
                        img{
                            @include width-height(65px,65px);
                        }
                    }
                    .itemb{
                        grid-area: b;
                        @include font-size-color(1.3rem,#000);
                        font-weight: bold;
                    }
                    .itemc{
                        grid-area: c;
                        @include font-size-color(0.8rem,#888);
                    }
                    .itemd{
                        grid-area: d;
                        padding-top: 0.3rem;
                        p{
                            display: inline;
                            @include font-size-color(0.8rem,#FFA500);
                            padding:0 0.2rem 0 0.2rem;
                            border-radius: 0.8rem;
                            border:1px solid orange;
                            text-align: center;
                        }
                    }
                    .iteme{
                        grid-area: e;
                        @include font-size-color(1.2rem,#FFA500);
                        font-weight: bold;
                    }
                    .itemf{
                        grid-area: f;
                        padding-right: 0.5rem;
                        text-align: right;
                        p{
                            display: inline-block;
                            @include font-size-color(1rem,#000);
                            line-height: 1.5rem;
                            padding:0;
                        }
                        .pbutton{
                            @include blue;
                            display: inline-block;
                            @include font-size-color(0.8rem,#fff);
                            border-radius: 50%;
                            text-align: center;
                            padding:0rem;
                            @include width-height(1.5rem,1.5rem);
                        }
                    }
                    .elbutton{
                        @include blue;
                        padding:0.3rem 0.5rem 0.3rem 0.5rem;
                        display: inline;
                        @include font-size-color(0.8rem,#fff);
                        border-radius: 1rem;
                    }
                }
            }
        }
        .shopFooter{
            @include width-height(100%,3.5rem);
            background-color: #555;
            position: fixed;
            z-index: 9999;
            bottom: 0;
            display: grid;
            grid-template-columns: 25% 47% 30%;
            grid-template-rows: 100%;
            .itema{
                background-color: #555;
                position: relative;
                .imgContainer{
                    background-color:#26a2ff;
                    @include width-height(65px,65px);
                    border-radius: 50%;
                    position: absolute;
                    right: 1rem;
                    bottom:0.5rem;
                    border:5px solid #555;
                    img{
                        padding:0.5rem 0 0 0.3rem;
                    }
                    .popnum{
                        @include font-size-color(1.2rem,#fff);
                        @include width-height(1.5rem,1.5rem);
                        background-color:red;
                        text-align: center;
                        border-radius: 50%;
                        position: absolute;
                        top: -6px;
                        right: -6px;
                    }
                }
            }
            .itemb{
                background-color: #555;
                padding-top: 0.3rem;
                p{
                    @include font-size-color(0.8rem,#fff);
                }
                .cost1{
                    @include font-size-color(1.2rem,#fff);
                    display: inline;
                }
                .cost2{
                    @include font-size-color(0.8rem,#fff);
                    text-decoration:line-through;
                    display: inline;
                }
            }
            .itemc{
                @include width-height(100%,100%);
                text-align: center;
                @include font-size-color(1.2rem,#fff);
                padding-top: 0.8rem;
                background-color: #4cd964;
            }
        }
        /deep/ .el-card_header{
            padding:2px 20px;
        }
        .drawerclass{
            bottom:3.5rem;
            position: absolute;
            width: 100%;
            @include white;
            img{
                float: right;
            }
            .cartBox{
                @include width-height(100%,4.5rem);
                background-color:#fff;
                margin-bottom: 0.3rem;
                // border-bottom:1px solid #666;
                display: grid;
                grid-template-columns: 24% 46% 30%;
                grid-template-rows: 33.33% 33.33% 33.33%;
                grid-template-areas: "a b b"
                                     "a c c"
                                     "a d d";
                .itema{
                    grid-area: a;
                }
                .itemb{
                    grid-area: b;
                    font-weight: bold;
                }
                .itemc{
                    grid-area: c;
                    text-align: right;
                    padding-right: 1.8rem;
                    p{
                        display: inline-block;
                        @include font-size-color(1rem,#000);
                        line-height: 1.5rem;
                        padding:0;
                    }
                    .pbutton{
                        @include blue;
                        display: inline-block;
                        @include font-size-color(0.8rem,#fff);
                        border-radius: 50%;
                        text-align: center;
                        padding:0rem;
                        @include width-height(1.5rem,1.5rem);
                    }
                }
                .itemd{
                    grid-area: d;
                    padding-right: 2rem;
                    font-weight: bold;
                    text-align: right;
                    @include font-size-color(1.3rem,#FFA500);
                }
            }
        }
        /deep/ .el-card{
            height: max-content !important;
        }
    }
</style>